#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SLInit(SL* ps)
{
	ps->_arr = NULL;
	ps->_capacity = ps->_size = 0;
}

void SLDestory(SL* ps)
{
	free(ps->_arr);
	ps->_arr = NULL;
	ps->_capacity = ps->_size = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->_size; ++i)
	{
		printf("%d ", ps->_arr[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->_capacity == ps->_size)
	{
		size_t newcapcity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
		int* tmp = (int*)realloc(ps->_arr,sizeof(int) * newcapcity);
		if (tmp == NULL)
		{
			return;
		}
		ps->_arr = tmp;
		ps->_capacity = newcapcity;
	}

}
void SLPushBack(SL* ps, int x)
{
	assert(ps);
	SLCheckCapacity(ps);

	ps->_arr[ps->_size++] = x;

}
void SLPushFront(SL* ps, int x)
{
	assert(ps);
	SLCheckCapacity(ps);

	size_t end = ps->_size;
	while (end > 0)
	{
		ps->_arr[end] = ps->_arr[end - 1];
		--end;
	}

	ps->_arr[0] = x;
	++ps->_size;
}

bool SLEmpty(SL* ps)
{
	return ps->_size == 0;
}
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(!SLEmpty(ps));

	--ps->_size;
}
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->_size);

	size_t start = 0;
	while (start < ps->_size)
	{
		ps->_arr[start] = ps->_arr[start + 1];
		++start;
	}

	--ps->_size;
}

int SLFind(SL* ps, int x)
{
	assert(ps);

	for (int i = 0; i < ps->_size; ++i)
	{
		if (ps->_arr[i] == x)
		{
			return i;
		}
	}
	
	return -1;
}

void SLInsert(SL* ps, int pos, int x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->_size);

	size_t end = ps->_size;
	while (end > pos)
	{
		ps->_arr[end] = ps->_arr[end - 1];
		--end;
	}
	ps->_arr[pos] = x;
	++ps->_size;
}

void SLErase(SL* ps,int pos)
{
	assert(ps);
	assert(ps->_size);

	size_t start = pos;
	while (start < ps->_size)
	{
		ps->_arr[start] = ps->_arr[start + 1];
		++start;
	}

	--ps->_size;
}
